package unipi.database;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class PrivateMessage 
{
	public static ErrorCodes send(String title, String body, String senderID, String recipientID)
	{
		String columns = "subject, body, dateSent, senderID, recipientID";
		String values = "'" + title + "', '" + body + "', now(), " + senderID + "," + recipientID;
		
		return SQLMethods.Insert("PrivateMessages", columns, values) != -1 ? ErrorCodes.OK : ErrorCodes.databaseError;		
	}
	
	public static List<List<String>> getUserRecipients(String uid)
	{
		int ncols = 3;
		String query = "select concat(u.surname, ' ', u.name), count(u.id), u.id\r\n" + 
						"from PrivateMessages pm\r\n" + 
						"inner join Users u \r\n" + 
						"on (pm.senderID + pm.recipientID - " + uid + ") = u.id\r\n" + 
						"where senderID = " + uid + " or recipientID = " + uid + "\r\n" + 
						"group by u.id";
		
		return SQLMethods.Select(query, ncols);
	}
	
	public static List<Map<String, String>> getConversation(String from, String to)
	{
		int ncols = 4;
		String query = "select subject, body, dateSent, senderID from PrivateMessages\r\n" + 
						"where senderID = " + from + " and recipientID = " + to + "\r\n" + 
						"or\r\n" + 
						"senderID = " + to + " and recipientID = " + from + "\r\n" + 
						"order by dateSent desc";		
		
		List<List<String>> convList = SQLMethods.Select(query, ncols);
		if(convList == null) return null;
		
		List<Map<String, String>> conv = new ArrayList<Map<String, String>>();
		
		for(List<String> row : convList)
		{
			Map<String, String> map = new HashMap<String, String>();
			map.put("subject", row.get(0));
			map.put("body", row.get(1));
			map.put("date", row.get(2));			
			map.put("bubble", (row.get(3).equals(from))?"left":"right");
			
			conv.add(map);
		}
		
		
		return conv;		
	}
	
}
